/*
 * @Author: xujianwei
 * @Date: 2021-05-31 14:12:09
 * @LastEditors: xujianwei
 * @LastEditTime: 2021-05-31 15:47:35
 */
const SSHClient = require('ssh2').Client
const client = require('scp2')
const ora = require('ora')
const conn = new SSHClient()

const fs = require('fs')
const data = fs.readFileSync('./dist/index.html', 'utf-8')

// 写入打包发布时间
fs.writeFileSync('./dist/index.html', data.replace('DEPLOY_INFO', `${Date().now()}`))

let config ={
    path: '/home/docker/nginx/blog',
    host: 'xldou.cn',
    username: 'root'
}

var prompt = require('prompt');
var schema = {
    properties: {
      password: {
        description:'请输入服务器密码：',
        hidden: true
      }
    }
  };

prompt.start();
prompt.get(schema, function (err, result) {
    if (err) throw err
    config.password = result.password
    const spinner = ora('正在发布到服务器...').start()
    conn
      .on('ready', function() {
        conn.exec(`rm -rf ${config.path}`, function(err, stream) {
          if (err) throw err
          spinner.text = '删除文件成功！'
          stream.on('close', function(code, signal) {
            spinner.text = '开始上传'
            client.scp('./dist', config, err => {
              if (err) {
                spinner.stop()
                console.log(err)
                throw err
              } else {
                spinner.succeed('上传成功')
              }
            })
            conn.end()
          })
        })
      })
      .connect(config)
});



